﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Word;

namespace MultiThumbnail.Converters
{
    /// <summary>
    /// To allow work it from service or IIS you need:
    /// 1. Run command dcomcnfg
    /// 2. Expand the Component Services->Computers->My Computer->DCOM Config (Службы компонентов->Компьютеры->Мой компьютер->Настройка DCOM
    /// 3. Find Microsoft Word Document (can be Документ Microsoft Word 93-2003)
    /// 4. Right mouse click->Properties. click the Identity tab. Check the "This user" checkbox.
    /// </summary>
    [Extension("DOCX;DOCM;DOC")]
    class DocThumbConverter : ThumbConverter
    {
        public override bool CreateMiniature(Stream fileStream, string resultPath)
        {
            return true;
        }

        protected override bool CreateMiniatureForFile(string path, string resultPath)
        {
            string filePathToRemove = null;
            try
            {
                //if (ext == null || ext.TrimStart('.').ToUpperInvariant() != ConverterSettings.CurrentExtension)
                //{
                filePathToRemove = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(path) + '.' + ConverterSettings.CurrentExtension);
                File.Copy(path, filePathToRemove, true);
                path = filePathToRemove;
                //}

                Convert(path, resultPath + ".pdf", WdSaveFormat.wdFormatPDF);
                try
                {
                    new PdfThumbConverter { ConverterSettings = ConverterSettings }.CreateMiniature(resultPath + ".pdf", resultPath);
                    return true;
                }
                finally
                {
                    File.Delete(resultPath + ".pdf");
                }
            }
            finally
            {
                if (filePathToRemove != null)
                    File.Delete(filePathToRemove);
            }
        }

        private static void Convert(string inputPath, string outputPath, WdSaveFormat format)
        {
            // Create an instance of Word.exe
            _Application oWord = new Application();

            // Make this instance of word invisible (Can still see it in the taskmgr).
            oWord.Visible = false;

            // Interop requires objects.
            object oMissing = System.Reflection.Missing.Value;
            object oInput = inputPath;
            object oOutput = outputPath;
            object oFormat = format;

            //If you have an error do:
            //
            //    Start -> dcomcnfg.exe
            //    Computer
            //    Local Computer
            //    Config DCOM
            //    Search for Microsoft Word 97-2003 Documents -> Properties
            //Tab Identity, change from Launching User to Interactive User 
            _Document oDoc = oWord.Documents.Open(ref oInput, false, true, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                oMissing, oMissing, true, oMissing);
            oDoc.Activate();
            oDoc.SaveAs(ref oOutput, ref oFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
        }
    }
}
